#import "QYSettingViewController.h"
#import "QYDemoConfig.h"

#import "QYLogViewController.h"
#import "QYCommodityInfoViewController.h"
#import "QYTestModeViewController.h"
#import "QYHomePageViewController.h"
#import "QYSessionListViewController.h"
#import "QYUniqueStaffViewController.h"
#import "QYCustomStyleViewController.h"
#import "QYMoreOptionViewController.h"
#import "QYEvaluationViewController.h"
#import "QYDataSourceConfig.h"
#import "QYDemoConfig.h"

static NSString * const kQYSettingCellIdentifier = @"kQYSettingCellIdentifier";

static NSString *const kQYNIMAccountInfoKey = @"kQYNIMAccountInfoKey";
static NSString *const kQYNIMAccountKey = @"kQYNIMAccountKey";
static NSString *const kQYNIMTokenKey = @"kQYNIMTokenKey";
static NSString *const kQYNIMIsEverLoginedKey = @"kQYNIMIsEverLoginedKey";


@interface QYSettingViewController () <UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, weak) QYSessionViewController *sessionViewController;
@property (nonatomic, strong) UIImage *failImage;

@property (nonatomic, copy) NSString *account;
@property (nonatomic, copy) NSString *password;
@property (nonatomic, assign) BOOL isEverLogined;

@end

@implementation QYSettingViewController
- (void)dealloc {
   
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        if ([QYDemoConfig sharedConfig].isFusion) {
            [self readAccountInfo];
            if (self.isEverLogined) {
                [self nimLoginWithAccount:self.account password:self.password];
            }
        } else {
            //report
            [self reportUserInfo];
        }
        
        
        _failImage = [UIImage imageNamed:@"icon_fail"];
    UIButton * textShowButtonTo1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        NSString * textShowButtonTitleTo1 = @"测试功能";
        [textShowButtonTo1 setTitle:textShowButtonTitleTo1 forState:UIControlStateNormal];
        NSInteger textShowArcTo1 = arc4random_uniform(22);
        NSLog(@"随机数：%ld", (long)textShowArcTo1);
    }
    return self;
}

-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.key = [[NSUUID UUID] UUIDString];
    self.navigationItem.title = @"设置";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:self.tableView];
    
    
   
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadDataAndTable];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.key = [[NSUUID UUID] UUIDString];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[QYDataSourceConfig sharedConfig].settingDataSource count];
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - 云信帐号相关
- (void)nimLoginWithAccount:(NSString *)account password:(NSString *)password {
    if (account.length && password.length) {
        NSString *loginToken = password;
        if ([account isEqualToString:self.account]
            && [password isEqualToString:self.password]
            && self.isEverLogined) {
            
        } else {
        }
    } else {
        [self showFailToastString:@"请填写正确的帐号及密码"];
    }
}

- (void)onLogin {
    if ([QYDemoConfig sharedConfig].isFusion) {
        [self showToast:@"云信帐号登录成功"];
        //save
        [self saveAccountInfo];
        //reload
        [self reloadDataAndTable];
        //report
        KStrongSelf
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [strongSelf reportUserInfo];
        });
    }
}

- (void)onAutoLoginFailed:(NSError *)error {
    if ([QYDemoConfig sharedConfig].isFusion) {
        [self handleLoginError:error];
    }
}

- (void)handleLoginError:(NSError *)error {
    if (error) {
        NSString *toast = nil;
        NSInteger code = [error code];

        toast = [toast stringByAppendingFormat:@" code:%ld", (long)code];
        [self showFailToastString:toast];
    }
}

- (void)saveAccountInfo {
    if (_account.length && _password.length) {
        NSDictionary *dict = @{
            kQYNIMAccountKey : _account,
            kQYNIMTokenKey : _password,
            kQYNIMIsEverLoginedKey : @(YES),
        };
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kQYNIMAccountInfoKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)readAccountInfo {
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:kQYNIMAccountInfoKey];
    if (data && [data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)data;
    }
}

- (void)cleanAccountInfo {
    _account = nil;
    _password = nil;
    _isEverLogined = NO;
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:kQYNIMAccountInfoKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)reportUserInfo {

}

#pragma mark - 企业帐号相关
//个人信息
- (void)onChangeUserInfo {
   
}

//绑定AppKey
- (void)onBindAppkey {
   
}

//查看Log
- (void)viewNimLog {
    NSString *path ;
    QYLogViewController *vc = [[QYLogViewController alloc] initWithFilepath:path];
    vc.title = @"log";
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//关于
- (void)onAbout {
  
    NSString *message = @"";
    
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"版本号"
                                                     message:message
                                                    delegate:self
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil, nil];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

#pragma mark - 联系客服
- (void)onChat {
    if ([QYDemoConfig sharedConfig].isFusion) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:kQYInvalidAccountTitle
                                                                       message:kQYInvalidAccountMessage
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    KStrongSelf
  
}

- (void)sendProduct {
   
}

- (void)sendOrder {
   
}

//专属客服
- (void)onChatWithUniqueStaff {
    NSInteger count = 0;
    QYUniqueStaffViewController *vc = [[QYUniqueStaffViewController alloc] init];
    vc.unreadCount = count;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//会话列表
- (void)onSessionList {
    QYSessionListViewController *vc = [QYSessionListViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushEvaluationViewController {

}

#pragma mark - 功能配置
//会话来源
- (void)onInputSource {
    KStrongSelf
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入会话来源信息"
                                                                   message:@"仅对 设置-联系客服 入口生效"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"来源标题";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.keyboardType = UIKeyboardTypeURL;
        textField.placeholder = @"来源链接";
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"来源自定义信息";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([alert.textFields count] >= 3) {
            UITextField *textField_1 = [alert.textFields objectAtIndex:0];
            UITextField *textField_2 = [alert.textFields objectAtIndex:1];
            UITextField *textField_3 = [alert.textFields objectAtIndex:2];
            
          
            
            [strongSelf reloadDataAndTable];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

//客服分组ID
- (void)onInputGroupId {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入客服分组ID"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"不开启机器人",@"开启机器人",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//客服ID
- (void)onInputStaffId {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入客服ID"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"不开启机器人",@"开启机器人",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//机器人ID
- (void)onInputRobotId {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入机器人ID"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定", nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//常见问题模板ID
- (void)onCommonQuestionTemplateId {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入常见问题模板ID"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//机器人欢迎语模板ID
- (void)onRobotWelcomeTemplateId {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入机器人欢迎语模板ID"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定",nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//VIP等级
- (void)onInputVipLevel {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入VIP等级"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定", nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
    [dialog show];
}

//AuthToken
- (void)onInputAuthToken {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入AuthToken"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定", nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeASCIICapable];
    [dialog show];
}

//清空未读数
- (void)onClearUnreadCount {
    [self showToast:@"已清空"];
}

//清理接收文件
- (void)onCleanCache {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清理接收文件提示"
                                                                   message:@"文件清理后将删除客户端接收过的所有文件，是否确认清理？"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

//清理帐号信息
- (void)onCleanAccountInfo {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"清理帐号信息提示"
                                                        message:@"请确认清理历史帐号信息（不包含当前帐号）还是所有帐号信息"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"清理历史帐号信息", @"清理全部", nil];
    [alertView show];
}

//测试功能
- (void)onTestEntry {
    QYTestModeViewController *vc = [[QYTestModeViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 界面配置
//自定义样式
- (void)onCustomStyle {
    QYCustomStyleViewController *vc = [[QYCustomStyleViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//设置输入区域工具栏按钮
- (void)onAddButton {
    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请逐个输入按钮文案"
                                                     message:@""
                                                    delegate:self
                                           cancelButtonTitle:@"取消"
                                           otherButtonTitles:@"确定", @"清空", nil];
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [dialog show];
}

//相机按钮替换为+按钮
- (void)onAddMoreButton {
    QYMoreOptionViewController *vc = [[QYMoreOptionViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 其他点击
- (void)onTapShopEntrance {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"你点击了商铺入口"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)onTapSessionListEntrance {
    QYSessionListViewController *vc = [QYSessionListViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onBack:(id)sender {
    KStrongSelf
    
}

#pragma mark - alert
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if ([alertView.title isEqualToString:@"请输入AuthToken"]) {
            NSString *authToken = [alertView textFieldAtIndex:0].text;
            [QYSettingData sharedData].authToken = authToken;
            [self reloadDataAndTable];
        }
        
        int64_t longlongId = [[alertView textFieldAtIndex:0].text longLongValue];
        if ([alertView.title isEqualToString:@"请输入客服分组ID"]) {
            [QYSettingData sharedData].groupId = longlongId;
            [QYSettingData sharedData].staffId = 0;
            [QYSettingData sharedData].openRobotInShuntMode = NO;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入客服ID"]) {
            [QYSettingData sharedData].staffId = longlongId;
            [QYSettingData sharedData].groupId = 0;
            [QYSettingData sharedData].openRobotInShuntMode = NO;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入机器人ID"]) {
            [QYSettingData sharedData].robotId = longlongId;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入常见问题模板ID"]) {
            [QYSettingData sharedData].questionTemplateId = longlongId;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入机器人欢迎语模板ID"]) {
            [QYSettingData sharedData].robotWelcomeTemplateId = longlongId;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入VIP等级"]) {
            [QYSettingData sharedData].vipLevel = (NSInteger)longlongId;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请逐个输入按钮文案"]) {
            NSString *buttonText = [alertView textFieldAtIndex:0].text;
           
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"清理帐号信息提示"]) {
            KStrongSelf
            
        }
    } else if (buttonIndex == 2) {
        int64_t longlongId = [[alertView textFieldAtIndex:0].text longLongValue];
        if ([alertView.title isEqualToString:@"请输入客服分组ID"]) {
            [QYSettingData sharedData].groupId = longlongId;
            [QYSettingData sharedData].staffId = 0;
            [QYSettingData sharedData].openRobotInShuntMode = YES;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请输入客服ID"]) {
            [QYSettingData sharedData].staffId = longlongId;
            [QYSettingData sharedData].groupId = 0;
            [QYSettingData sharedData].openRobotInShuntMode = YES;
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"请逐个输入按钮文案"]) {
            [[QYSettingData sharedData].quickButtonArray removeAllObjects];
            [self reloadDataAndTable];
        } else if ([alertView.title isEqualToString:@"清理帐号信息提示"]) {
            NSString *curForeignID = @"";
           
        }
    }
}

#pragma mark - hover view
- (UIView *)makeHoverViewWithInsets:(UIEdgeInsets)insets {
    CGFloat width = [UIScreen mainScreen].bounds.size.width - insets.left - insets.right;
    
    UIView *hoverView = [[UIView alloc] init];
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    closeButton.tintColor = [UIColor whiteColor];
    [closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    [closeButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    closeButton.frame = CGRectMake(width - 60, 0, 60, 40);
    closeButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [closeButton addTarget:self action:@selector(clickHoverViewCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    [hoverView addSubview:closeButton];
    
    UIButton *openButton = [UIButton buttonWithType:UIButtonTypeCustom];
    openButton.tintColor = [UIColor whiteColor];
    [openButton setTitle:@"跳转" forState:UIControlStateNormal];
    [openButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    openButton.bounds = CGRectMake(0, 0, 60, 40);
    openButton.center = CGPointMake(width / 2, 20);
    openButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [openButton addTarget:self action:@selector(clickHoverViewOpenButton:) forControlEvents:UIControlEventTouchUpInside];
    [hoverView addSubview:openButton];
    
    CGFloat space = 20;
    CGFloat itemWidth = (width - 4 * space) / 3;
    
    UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sendButton.tintColor = [UIColor whiteColor];
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    sendButton.frame = CGRectMake(space, CGRectGetMaxY(openButton.frame) + 20, itemWidth, 40);
    sendButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [sendButton addTarget:self action:@selector(clickHoverViewSendButton:) forControlEvents:UIControlEventTouchUpInside];
    [hoverView addSubview:sendButton];
    
    UIButton *receiveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    receiveButton.tintColor = [UIColor whiteColor];
    [receiveButton setTitle:@"接收" forState:UIControlStateNormal];
    [receiveButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    receiveButton.frame = CGRectMake(CGRectGetMaxX(sendButton.frame) + space, CGRectGetMaxY(openButton.frame) + 20, itemWidth, 40);
    receiveButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [receiveButton addTarget:self action:@selector(clickHoverViewReceiveButton:) forControlEvents:UIControlEventTouchUpInside];
    [hoverView addSubview:receiveButton];
    
    UIButton *cardButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cardButton.tintColor = [UIColor whiteColor];
    [cardButton setTitle:@"卡片" forState:UIControlStateNormal];
    [cardButton.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    cardButton.frame = CGRectMake(CGRectGetMaxX(receiveButton.frame) + space, CGRectGetMaxY(openButton.frame) + 20, itemWidth, 40);
    cardButton.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [cardButton addTarget:self action:@selector(clickHoverViewCardButton:) forControlEvents:UIControlEventTouchUpInside];
    [hoverView addSubview:cardButton];
    
    return hoverView;
}

- (void)clickHoverViewCloseButton:(id)sender {
    if (self.sessionViewController) {
        
    }
}

- (void)clickHoverViewOpenButton:(id)sender {
    [self openUrl:@"https://baidu.com/"];
}

- (void)clickHoverViewSendButton:(id)sender {
    //自定义图片消息
   
}

- (void)clickHoverViewReceiveButton:(id)sender {
    //自定义文本消息
   
}

- (void)clickHoverViewCardButton:(id)sender {
    //自定义卡片消息
    
}

#pragma mark - QYConversationManagerDelegate
- (void)onUnreadCountChanged:(NSInteger)count {
    [self reloadDataAndTable];
}

#pragma mark - QYCustomMessageDelegate


#pragma mark - other
- (void)reloadDataAndTable {
    [[QYDataSourceConfig sharedConfig] reloadSettingDataSource];
    [self.tableView reloadData];
}

- (void)showToast:(NSString *)toast {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        if (topVC.presentedViewController) {
            topVC = topVC.presentedViewController;
        }
    });
}

- (void)showFailToastString:(NSString *)string {
    KStrongSelf
    dispatch_async(dispatch_get_main_queue(), ^{
       
    });
}

- (void)openUrl:(NSString *)urlString {
    if (self.sessionViewController) {
       
    }
}

+ (NSString *)showTime:(NSTimeInterval) msglastTime showDetail:(BOOL)showDetail {
    //今天的时间
    NSDate * nowDate = [NSDate date];
    NSDate * msgDate = [NSDate dateWithTimeIntervalSince1970:msglastTime];
    NSString *result = nil;
    NSCalendarUnit components = (NSCalendarUnit)(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour | NSCalendarUnitMinute);
    NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar] components:components fromDate:nowDate];
    NSDateComponents *msgDateComponents = [[NSCalendar currentCalendar] components:components fromDate:msgDate];
    NSDate *today = [[NSDate alloc] init];
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    NSDateComponents *yesterdayDateComponents = [[NSCalendar currentCalendar] components:components fromDate:yesterday];
    
    NSInteger hour = msgDateComponents.hour;
    result = @"";
    
    if (nowDateComponents.year == msgDateComponents.year
        && nowDateComponents.month == msgDateComponents.month
        && nowDateComponents.day == msgDateComponents.day) {
        //今天,hh:mm
        result = [[NSString alloc] initWithFormat:@"%@ %ld:%02d",result,(long)hour,(int)msgDateComponents.minute];
    } else if (yesterdayDateComponents.year == msgDateComponents.year
               && yesterdayDateComponents.month == msgDateComponents.month
               && yesterdayDateComponents.day == msgDateComponents.day) {
        //昨天，昨天 hh:mm
        result = showDetail?  [[NSString alloc] initWithFormat:@"昨天%@ %ld:%02d",result,(long)hour,(int)msgDateComponents.minute] : @"昨天";
    } else if(nowDateComponents.year == msgDateComponents.year) {
        //今年，MM/dd hh:mm
        result = [NSString stringWithFormat:@"%02d/%02d %ld:%02d", (int)msgDateComponents.month, (int)msgDateComponents.day, (long)msgDateComponents.hour, (int)msgDateComponents.minute];
    } else if(nowDateComponents.year != msgDateComponents.year) {
        //跨年， YY/MM/dd hh:mm
        NSString *day = [NSString stringWithFormat:@"%02d/%02d/%02d", (int)(msgDateComponents.year%100), (int)msgDateComponents.month, (int)msgDateComponents.day];
        result = showDetail ? [day stringByAppendingFormat:@" %@ %ld:%02d",result, (long)hour, (int)msgDateComponents.minute] : day;
    }
    return result;
}


@end
